/*************************************************
 * 
 * Copyright by Bruno Eberhard
 * 
 * Created on 24.06.2006
 *
 *************************************************/
package fightplan.business;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import fightplan.core.Util;

/**
 * Ein FightEntry ist ein "Teilnehmerplatz" bei einem Kampf. Bei einem KO-System
 * hat ein Kampf immer genau zwei FightEntry, bei einem Gruppensystem hat ein
 * Kampf vielleicht 5 FightEntry.
 * 
 * Jeder Entry kennt seinen Fight und meldet diesem Änderungen an dem eigenen
 * FighterHolder.
 */
public class FightEntry implements PropertyChangeListener, Serializable {
	private static final long serialVersionUID = 1L;

	private Fight fight;
	private FighterProvider fighter;
	private Result result;
	private List<Float> scores;

	//

	public FightEntry(Fight fight, FighterProvider fighter) {
		if (fight == null)
			throw new IllegalArgumentException();
		this.fight = fight;
		this.fighter = fighter;
		if (fighter instanceof FighterHolder) {
			((FighterHolder) fighter).addPersistentChangeListener(this);
		}
		result = Result.OPEN;
	}

	// get/set

	public FighterProvider getFighterProvider() {
		return fighter;
	}

	AbstractFighter getFighter() {
		return fighter.getFighter();
	}

	public Float getOverallScore() {
		if (scores == null)
			return 0.0F;

		Float score = 0.0F;

		// Die schlechteste und die beste Wertung wird weggelassen
		Float min = Float.MAX_VALUE;
		Float max = Float.MIN_VALUE;

		for (Float s : scores) {
			if (s > max) {
				max = s;
			}
			if (s < min) {
				min = s;
			}
			score += s;
		}

		score = Math.max(score - min - max, 0);
		return score;
	}

	public Float getScore(int pos) {
		if (scores == null || scores.size() <= pos)
			return 0.0F;

		return scores.get(pos);
	}

	public void setScore(int pos, Float score) {
		if (scores == null) {
			scores = new ArrayList<Float>();
		}

		while (scores.size() <= pos) {
			scores.add(0F);
		}

		scores.set(pos, score);
		fight.entryChanged(this);
	}

	public List<Float> getScores() {
		return scores;
	}

	public void setScores(List<Float> scores) {
		this.scores = scores;
	}

	public Result getResult() {
		return result;
	}

	public void setResult(Result result) {
		if (Util.equals(this.result, result))
			return;
		this.result = result;
		fight.entryChanged(this);
	}

	// PropertyChangeListener

	public void propertyChange(PropertyChangeEvent evt) {
		fight.entryChanged(this);
	}

}